<template>
  <t-adaptive-page
      v-loading="state.loading"
      class="menu_mange"
      tableTitle="回款单列表"
      row-key="path"
      isCopy
      ref="tAdaptivePageRef"
      show-summary
      isExpansion
      :isTTableSelfFilling="false"
      :isShowPagination="false"
      columnSetting
      :table="state.table"
      :columns="state.table.columns"
      isShowWidthSize
      :opts="opts"
      :widthSize="4"
      @submit="conditionEnter"
      @radio-change="selecUpdateChange"
  >
    <template #CreateDate="{scope}">
      <div>{{ parseTime(scope.row.CreateDate) }}</div>
    </template>

    <template #State="{scope}">
      <el-tag type="info" v-if="scope.row.State=='0'">开立</el-tag>
      <el-tag type="success" v-if="scope.row.State=='2'">已审核</el-tag>
      <el-tag type="primary" v-if="scope.row.State=='1'">送审中</el-tag>
      <el-tag type="danger" v-if="scope.row.State=='3'">已关闭</el-tag>
    </template>

    <template #footerBtn>
      <el-button type="danger" @click="addHandle()" v-if="checkPermission('新增', state.roleList)">新增</el-button>
      <el-button type="danger" @click="deleteHandles" :disabled="!state.ids.length" v-if="checkPermission('删除', state.roleList)">删除</el-button>

      <el-button type="primary" @click="tAdaptivePageRef.TQueryConditionPage.checkHandle()">查询</el-button>
      <el-button type="danger" @click="tAdaptivePageRef.TQueryConditionPage.resetHandle()">重置</el-button>
    </template>
    <template #toolbar>
      <div v-if="state.selectedRow">
        <el-button type="primary"  @click="handlEedit(state.selectedRow)"  v-if="['0'].includes(state.selectedRow.State) && checkPermission('修改', state.roleList)">编辑</el-button>
        <el-button type="primary"  @click="deleteHandles(state.selectedRow)" v-if="['0'].includes(state.selectedRow.State) && checkPermission('删除', state.roleList)">删除</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow,'2')" v-if="['0'].includes(state.selectedRow.State) && checkPermission('审核', state.roleList)">审核</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow, '0')" v-if="['2'].includes(state.selectedRow.State) && checkPermission('弃审', state.roleList)">弃审</el-button>
        <el-button type="primary"  @click="handlCheck(state.selectedRow,'3')"  v-if="state.selectedRow.State!=='3' && checkPermission('关闭', state.roleList)" >关闭</el-button>
      </div>
      <div v-else style="color:red">
        选择数据后显示操作按钮
      </div>

    </template>

    <template #cCode="{ scope }">
      <div>
        <el-link
            link
            @click="viewCheck(scope.row)"
            type="primary"
        >{{ scope.row.cCode }}</el-link>
      </div>
    </template>


  </t-adaptive-page>
  <!--  新增 / 修改-->
  <el-dialog :title="state.title" width="60%" v-model="state.dialogSelectEnt" draggable :close-on-click-modal="false" @close="closeDialog">
    <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-position="right" >
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="客户" prop="CustName">
            <el-select
                v-model="state.formData.CustName"
                filterable
                remote
                reserve-keyword
                placeholder="请选择客户"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                @change="changeCustCode"
                remote-show-suffix
            >
              <el-option
                  v-for="item in cusoptions"
                  :key="item.ccusabbname"
                  :label="item.ccusabbname"
                  :value="item.ccusabbname">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="实收金额" prop="Amount">
            <el-input v-model="state.formData.Amount" placeholder="请输入收款实收金额" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <t-layout-page-item>
      <t-table
          title="明细"
          show-summary
          width="100%"
          ref="singleEdit"
          :table="state.clumTable"
          :columns="state.clumTable.columns"
          :isShowPagination="false"
          :listTypeInfo="state.clumTable.listTypeInfo"
      >
        <template #toolbar>
          <t-select-table
              ref="selectTable_c"
              :table="state.editTable"
              :columns="state.editTable.columns"
              :max-height="400"
              multiple
              :defaultSelectVal="state.defaultSelectVal"
              @selectionChange="selectionChange"
              :keywords="{ label: 'CustName', value: 'ContractNum' }"
          ></t-select-table>
          <el-button style="margin-left: 15px" type="primary" @click="addToTable">确认选择</el-button>
        </template>
      </t-table>

    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>


  <!--  详情-->
  <el-dialog :title="state.detail.title" width="60%" v-model="state.detail.dialogSelectEnt" draggable :close-on-click-modal="false" @close="closeDialog">
    <el-form ref="formRef" :model="state.detail.formData" :rules="state.rules" label-position="right" disabled>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="客户" prop="CustName">
            <el-select
                v-model="state.detail.formData.CustName"
                filterable
                remote
                reserve-keyword
                placeholder="请选择客户"
                :remote-method="cnvbasdocMethod"
                :loading="state.loading"
                @change="changeCustCode"
                remote-show-suffix
            >
              <el-option
                  v-for="item in cusoptions"
                  :key="item.ccusabbname"
                  :label="item.ccusabbname"
                  :value="item.ccusabbname">
                <span style="float: left">{{ item.ccusabbname }}</span>
                <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">【{{item.cCusCode}}】</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="实收金额" prop="Amount">
            <el-input v-model="state.detail.formData.Amount" placeholder="请输入收款实收金额" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <t-layout-page-item>
      <el-table :data="state.detail.gridData">
        <el-table-column label="合同编号" prop="ContractNum"></el-table-column>
        <el-table-column label="收款金额" prop="Amount"></el-table-column>
        <el-table-column label="税率" prop="Rate"></el-table-column>
        <el-table-column label="税额" prop="Tax"></el-table-column>
        <el-table-column label="不含税金额" prop="iNatAmount"></el-table-column>
      </el-table>


    </t-layout-page-item>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup lang="tsx">
import {computed, onMounted, reactive, ref, toRefs, unref, watch} from "vue"
import {selcetDataList,saveSKD,getOneSKD,delSKD} from "@/api/contract_payment"
import {getContractInfo,GetSKJHByHT,ApproveDocument,userRole} from "@/api/base"
import {parseTime,checkPermission} from "@/utils/util";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {ElMessage} from "element-plus";

const tAdaptivePageRef: any = ref(null)


const cubasdoc = cubasdocStore()
const handlEedit = async (row: any)  => {

  let {Data} = await getOneSKD({id:row.Id})
  state.formData = Data.Main
  state.clumTable.data = Data.SubLists


  //过滤合同
  let contractInfo = cubasdoc.contractList.filter((item: any) => item.CustName == row.CustName)
  if (contractInfo){
    state.editTable.data = JSON.parse(JSON.stringify(contractInfo));

    state.defaultSelectVal = Data.SubLists.map((item: any) => item.ContractNum)
    state.dialogSelectEnt = true
  }

}


const viewCheck = async (row: any)  =>{
  let {Data} = await getOneSKD({id:row.Id})
  state.detail.formData = Data.Main
  state.detail.gridData = Data.SubLists
  state.detail.dialogSelectEnt = true
}




const handleDelete = (row: any) => {

  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}

// 数量change事件
const numChange = (val, prop, scope) => {

  let newVar = state.clumTable.data[scope.$index].Amount
  state.clumTable.data[scope.$index].Tax= (newVar * state.clumTable.data[scope.$index].Rate / 100).toFixed(2)
  state.clumTable.data[scope.$index].iNatAmount= (newVar - (newVar * state.clumTable.data[scope.$index].Rate / 100)).toFixed(2)

  state.formData.Amount = Number(state.clumTable.data.reduce((a, b) => a + b.Amount, 0)).toFixed(2)

}


//表格配置
const state: any = reactive({
  roleList:[],
  queryData: {
    cCode:null,
    JobNum: null, // 登录名
    ContractNum: null, // 用户状态
    CreateFrom: null,
    CreateTo: null,
    CreateBy: null,
  },
  table: {
    border: true,
    // 接口返回数据
    data: [],
    firstColumn: { type: "radio", fixed: true },
    // 表头数据
    columns: [
      { prop: "cCode", label: "回款单号", minWidth: 120,fixed: 'left',slotName: 'cCode' },
      { prop: "CustName", label: "客户名称",minWidth: 180,fixed: 'left' },
      { prop: 'State', label: '状态', minWidth: 100, slotName: 'State' },
      { prop: "Amount", label: "实收金额",minWidth: 110},
      { prop: "CreateDate", label: "建单日期", minWidth: 160,slotName: "CreateDate"},
      { prop: "CreateBy", label: "建单人", minWidth: 110 },
      { prop: "ApproveDate", label: "审核日期", minWidth: 160,slotName: "ApproveDate"},
      { prop: "ApproveBy", label: "审核人", minWidth: 110 },
    ],
  },
  loading:false,
  title: "新增回款单",
  dialogSelectEnt:false,
  formData: {
    JobNum: null, // 工作号
    ContractNum: null, // 合同号
    cCode: null,
    CustName: null,
    ContractAmount: null,
    Amount: null,
    CreateFrom: null,
    CreateTo: null,
    CreateBy: null,
    EntryName:null,
   },
  coseData:[],

  clumTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [

      {
        prop: "ContractNum",
        label: "合同编码",
        minWidth: "160",
      },
      {
        prop: "Amount",
        label: "收款金额",
        canEdit: true,
        minWidth: "120",
        configEdit: {
          label: "收款金额",
          type: "input",
          editComponent: "el-input",
          eventHandle: {
            change: ({ val, prop, scope }) => numChange(val, prop, scope)
          }
        }
      },
      {
        prop: "Rate",
        minWidth: "120",
        label: "税率",
      },
      {
        prop: "Tax",
        minWidth: "120",
        label: "税额",
      },
      {
        prop: "iNatAmount",
        minWidth: "120",
        label: "不含税金额",
      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: "selection", fixed: true },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "ContractNum",
        label: "合同编号",
        width:150,
      },
      {
        prop: "ProjectName",
        label: "项目名称",
        width:150,
      },
      {
        prop: "JobNum",
        label: "工作号",
        width:150,
      },
      {
        prop: "ContractAmount",
        label: "合同金额",
        width:150,
      },
      {
        prop: "YSKAmount",
        label: "已收款金额",
      },
    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },

  rules:{
    CustName: [
      { required: true, message: '请选择客户', trigger: 'change' },
    ],
    EntryName: [
      { required: true, message: '请输入项目名称', trigger: 'change' },
    ],
    JobNum: [
      { required: true, message: '请输入工作号', trigger: 'blur' },
    ],
    Amount: [
      { required: true, message: '请输入实收金额', trigger: 'blur' },
    ],
    ContractAmount: [
      { required: true, message: '请输入应收金额', trigger: 'blur' },
    ],
  },
  defaultSelectVal:[],
  ids:[],
  skjhdList:[],
  selectedRow:null,
  detail:{
    dialogSelectEnt:false,
    title:'详情'
  }
})


//表单配置
const opts = ref({
  cCode: {
    label: "回款单号",
    comp: "el-input"
  },

  CreateFrom: {
    label: "制单日期",
    comp: "t-date-picker",
    span: 2,
    bind: {
      type: "daterange"
    }
  },
  CreateBy: {
    label: "建单人",
    comp: "el-input"
  },
})

//选择项
const cusoptions = ref([])


// 最终参数获取
const getQueryData = computed(() => {
  const { cCode, CreateFrom, CreateBy } = toRefs(
      state.queryData
  )
  return {
    cCode: cCode.value,
    CreateBy: CreateBy.value,
    CreateFrom: CreateFrom.value && CreateFrom.value[0] ? CreateFrom.value[0] : null,
    CreateTo: CreateFrom.value && CreateFrom.value[1] ? CreateFrom.value[1] : null,
  }
})

// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data

  getData()
}

//页面加载查询后端数据
onMounted(() => {
  getData()
  initRoleList()
})

// 获取数据
const getData = async () => {
  state.loading = true
  let data=await selcetDataList(getQueryData.value);

 // state.table.data = data;
  if (data.Code==='OK'){
    state.table.data = data.Data
  }
  state.loading = false
}

//过滤单位
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = cubasdoc.data
  }
}


//客户选择
function changeCustCode(e){
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.filter(item=> item.CustName===e);

  if (contractInfo){

    state.editTable.data = JSON.parse(JSON.stringify(contractInfo));

  }
}


//查询合同详细信息
async function findContractInfo (id) {
  let {Data}=await getContractInfo({id: id})

  const slist = [];
  if (Data?.SubList2){
    let rate = (Data.Main.Rate /100 ) +1
      //赋值合同明细转换
    for(var i=0;i<Data.SubList2.length;i++){
      const subdata = {
        "Id":null,
        "MID":null,
        "ConSubId":Data.SubList2[i].Id,//合同标的
        "InvCode":Data.SubList2[i].CinvCode,//存货编码
        "InvName":Data.SubList2[i].CinvName,//存货名称
        "InvStd":Data.SubList2[i].CinvAdd,//规格型号
        "Quantity":Data.SubList2[i].Quantity,//数量
        "Unit":Data.SubList2[i].Unit,//单位
        "iNatPrice":(Data.SubList2[i].Price / rate).toFixed(5),//不含税单价=含税单价 / 1.13
        "iNatAmount":(Data.SubList2[i].Amount / rate).toFixed(2),//不含税金额 = 含税金额 * 1.13
        "Rate":Data.Main.Rate,
        "Price":Data.SubList2[i].Price,//含税单价
        "ContractAmount":Data.SubList2[i].ContractAmount,//标的应收金额
        "Amount":Data.SubList2[i].Amount,//实收金额
        "Amounts":(Number(Data.SubList2[i].Quantity) * Number(Data.SubList2[i].Price)).toFixed(2),
        "Tax":(Data.SubList2[i].Amount - (Data.SubList2[i].Amount / rate)).toFixed(2),//税额
        "Remark":"",
      }
      slist.push(subdata);
    }
    //赋值合同明细
    state.editTable.data = slist;
    //赋值合同明细
    // state.editTable.data = Data.SubList

  }


}


//打开新增窗口
function addHandle() {
  reset()
  state.dialogSelectEnt = true
}

//关闭弹窗
function closeDialog() {
  reset()
  state.dialogSelectEnt = false
  state.detail.dialogSelectEnt=false
}

// 添加数据条数
const num = ref(1)
const singleEdit: any = ref(null)
const selectTable_c= ref(null)
// 添加数据
const add = () => {
  if (num.value > 0) {
    for (let i = 0; i < num.value; i++) {
      state.editTable.data.push({})
    }
  }
}
// 重置表单
const reset = () => {
  state.formData = {}
  state.coseData= []
  state.defaultSelectVal=[]
  state.editTable.data=[]
  selectTable_c.value?.clear()
  singleEdit.value?.resetFields()
}

//下拉表格选择数据
const selectionChange = (e) => {
  state.coseData = e

}

//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.selectedRow = e
}


//选择标的
const addToTable = () => {

  if (state.coseData.length<=0){
    ElNotification.error({
      title: '提示',
      message: '请选择合同',
      offset: 200,
    })
    return
  }



  state.coseData.forEach(item=>{
    //相同数据不能添加
    if (state.clumTable.data.find(item1=>item1.ContractId===item.Id)){
      ElNotification.error({
        title: '提示',
        message: '合同【'+item.ContractNum+'】已存在，请勿重复添加',
        offset: 200,
      })
      return
    }
    let newVar = (Number(item.ContractAmount) - (item.YSKAmount ? Number(item.YSKAmount):0))
    let Quantity ={
      ...item,
      ContractId:item.Id,
      Rate:item.Rate,
      ContractNum: item.ContractNum,
      Amount: newVar,
      Tax: (newVar * item.Rate / 100).toFixed(2),
      iNatAmount: (newVar - (newVar * item.Rate / 100)).toFixed(2)
    }
    state.clumTable.data.push(Quantity)
  })

  state.formData.Amount = state.clumTable.data.reduce((a, b) => a + b.Amount, 0)
}


const handlCheck = async (row: any,status: any)  => {
  //调用查询合同详细信息
  const ids = [row.Id];
  let data={
    "Ids": ids,  //单据id
    "Type":"SKD",  //类型 HTLR 合同录入 TDYS 通电验收  FHYS 发货验收  JSD 结算单  SKJH 收款计划 SKD 收款单 YKP 预收款发票
    "State":status,
  }
  await ApproveDocument(data);
  ElMessage.success("审核成功")
  await getData()
}



//校验表单需要定义ref
let formRef =ref({})
// 提交表单
function submitForm() {
  //校验提交表单
  formRef.value.validate(async (vaild) => {
    if (vaild){
      if (state.clumTable.data.length<=0){
        return ElMessage({
          message: '请选择合同',
          type: 'warning'
        })
        return
      }
      let data={
        Main: {
          ...state.formData,
          State: '0',
        },
        SubLists:state.clumTable.data
      }

     let res= await saveSKD(data)
      if (res.Code==='OK'){
        ElNotification.success({
          title: '提示',
          message: '保存成功',
          offset: 200,
        })
        closeDialog()
        await getData()

      }else{
        ElNotification.error({
          title: '提示',
          message: res.Result,
          offset: 200,
        })

      }

    }
  })


}


//删除表单
function deleteHandles(row) {

  const ids = row.Id ? [row.Id] : state.ids;


  ElMessageBox.confirm(
      '请仔细核对数据，删除后无法恢复！',
      '审核提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        delSKD({Ids:ids})
        ElMessage({
          type: 'success',
          message: '删除成功',
        })

        getData()
      })
      .catch(() => {

      })
}



const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同回款单' })
  state.roleList = res.items
}

</script>
